import "babel-polyfill";
import fly from './interceptor';
import Swiper from 'swiper/dist/js/swiper.js'; // 解决iphone6  https://github.com/nolimits4web/Swiper/issues/2263
import template from '../lib/art-template@4.13.2';
import clipboard from 'clipboard';
import auth from './auth';
import {
    hasClass,
    addClass,
    removeClass,
    getQueryString
} from '../js/utils';
import {
    baseUrl
} from './config';


// Methods
class MyView {
    constructor() {
        this.data = this.data();
        // type：猪符类别，若为0则代表常规进入，即不是从猪符分享进入
        // huse：猪符使用情况。1：未使用，2：已使用
        this.type = getQueryString("type");
        this.huse = getQueryString("huse");

        this.root = document.getElementById('root');
        this.btnSlider = document.getElementById("btnSlider");
        this.swiperSlider = document.getElementById("swiperSlider");
        this.alertContent = document.getElementById("alertContent");
        this.alertWraper = document.getElementById("alertWraper");
        this.btnWarper = document.getElementById("btnWarper");
        this.clipboard = null;

        this.myaudio = document.getElementById('myaudio');
    }
    data() {
        return {
            baseurl: "http://cloudlet.fengdao168.com/images/",
            my_pigticket: [], // 用户猪符列表
            myticket: {}, // 我的电影票数据
            audioStaus: false, // 音频是否播放
        }
    }
    init() {
        this.ready();
        this.showWelcomeAlert(); // 判断用户进入页面的方式们是否有猪符
        this.getmypigticket();
        auth.requestConfig(); // 微信授权
    }
    ready() {
        // ios微信音频自动播放
        document.addEventListener("WeixinJSBridgeReady", () => {
            this.myaudio.play();
        }, false);

        // 点击事件监听
        document.addEventListener('touchstart', (e) => {
            let target = e.target;
            // 弹窗容器关闭事件
            if (target.className.indexOf('alertclose') > -1) {
                this.alertWraper.style.display = 'none';
            }
            if (!this.data.audioStaus) {
                this.myaudio.play();
                this.data.audioStaus = true;
            }
            
        }, false)


    }
    async getmypigticket() {
        let res = await fly.post("/index/index/my_pigticket");
        if (res.code != 1) {
            this.showcommonAlert({
                word: res.msg || '网络错误',
                isshare: false
            })
            return;
        }
        this.data.my_pigticket = res.result.pigticket;
        this.renderSwiperSlider();
        this.renderSwiperBtns();
        this.renderSwiper();
        this.renderBtns(res.result);
    }
    renderSwiperBtns() {
        let html = template('pagination', {
            my_pigticket: this.data.my_pigticket
        });
        this.btnSlider.innerHTML = html;
    }
    renderSwiperSlider() {
        let html = template('swiperTempl', {
            my_pigticket: this.data.my_pigticket
        });
        this.swiperSlider.innerHTML = html;
    }
    renderSwiper() {
        let swiperBtns = new Swiper('#swiperBtns', {
            spaceBetween: 0,
            slidesPerView: 5,
            loop: false,
            freeMode: false,
            loopedSlides: 5, //looped slides should be the same
            watchSlidesVisibility: true,
            watchSlidesProgress: true,
        });

        let myswiper = new Swiper('#myswiper', {
            loop: false,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            thumbs: {
                swiper: swiperBtns,
            }
        })
    }
    renderTicketAlert(params) {
        let html = template('tiketTmpl', {
            code: params.code
        });
        this.alertContent.innerHTML = html;
        this.alertWraper.style.display = 'block';
    }
    renderMyTicketAlert(params) {
        let html = template('mytiketTmpl', {
            code: params.code
        });
        this.alertContent.innerHTML = html;
        this.alertWraper.style.display = 'block';
    }
    renderBtns(params) {
        let html = template('btnTmpl', {
            btn_type: params.btn_type
        });
        this.btnWarper.innerHTML = html;
    }
    async exchangeTicket() {
        let res = await fly.post("/index/index/get_movie");
        if (res.code != 1) {
            this.showcommonAlert({
                word: res.msg || '网络错误',
                isshare: false
            })
            return;
        }
        this.renderMyTicketAlert(res.result); // 查看我的电影票
        this.getmypigticket(); // 重置猪福
    }
    async showMyTicket() {
        if (!this.data.myticket.code) {
            let res = await fly.post("/index/index/my_movie");
            if (res.code != 1) {
                this.showcommonAlert({
                    word: res.msg || '网络错误',
                    isshare: false
                })
                return;
            }
            this.data.myticket = res.result;
        }
        this.renderMyTicketAlert(this.data.myticket); // 查看我的电影票
    }
    showcommonAlert(params) {
        let html = template('playagainTmpl', params);
        this.alertContent.innerHTML = html;
        this.alertWraper.style.display = 'block';
    }
    playAgain() {
        this.showcommonAlert({
            word: '分享至朋友或朋友圈即可再玩一次，你的“五福”近在咫尺',
            isshare: true
        })
    }
    async giveFriend(type) {
        let payload = `data=${JSON.stringify({type: type})}`;
        let res = await fly.post("/index/index/share_ticket", payload);
        if (res.code != 1) {
            this.showcommonAlert({
                word: res.msg || '网络错误',
                isshare: false
            })
            return;
        }
        this.getmypigticket(); // 重置猪福

        location.href = "./save.html?saveImg=" + encodeURIComponent(res.result);
        // this.renderGiveFriendAlert(res.result);

    }
    renderGiveFriendAlert(src) {
        let html = template('giveFriendTmpl', {
            src: src
        });
        this.alertContent.innerHTML = html;
        this.alertWraper.style.display = 'block';
    }
    flip(type) {
        let id = "flip_" + type;
        let ele = document.getElementById(id);
        let pulldown = document.getElementById("pulldown_" + type);
        if (hasClass(ele, 'flip')) {
            removeClass(ele, 'flip');
            pulldown.src = "http://cdn.fedau.com/project/weida/user_pic_pull_1.png";
        } else {
            addClass(ele, 'flip');
            pulldown.src = "http://cdn.fedau.com/project/weida/user_pic_pull_2.png";
        }
    }
    getYh(type) {
        if (this.clipboard) return;
        this.clipboard = new clipboard('.getYhBtn')
        this.clipboard.on('success', (e) => {
            this.showcommonAlert({
                word: '领取成功，立即打开手机淘宝即可看到',
                isshare: false
            })
        });
        this.clipboard.on('error', (e) => {
            this.showcommonAlert({
                word: '领取失败，请稍后再试',
                isshare: false
            })
        });
    }
    showWelcomeAlert() {
        if (this.type != 0) {
            if (this.huse == 1) {
                // 猪符未使用
                this.renderAlert({
                    className: "alertGameBig",
                    type: 'welcomeAlert',
                    imgsrc: `${baseUrl}fu_pic${this.type}.png`,
                    alertWord: '领取“<span class="mark">猪福</span>”, 逛维达庙会，集福兑换维达猪年好礼！',
                    btnword: '立即领取'
                })
            } else if (this.huse == 2) {
                // 已使用
                this.renderAlert({
                    className: "alertGameBig",
                    type: 'welcomeAlert',
                    imgsrc: `${baseUrl}user_pic_none${this.type}.png`,
                    alertWord: '啊偶~你来晚啦，“<span class="mark">猪福</span>”已经被领走了，去维达庙会逛逛蹭点福气吧！',
                    btnword: ''
                })
            }
        }
    }
    renderAlert(params) {
        let html = template('welcomeAlertTmpl', params);
        this.alertContent.innerHTML = html;
        this.alertWraper.style.display = 'block';
    }
    // 处理弹窗页按钮点击事件
    handleAlertClick(type) {
        if (!type) return;
        this.alertWraper.style.display = 'none';
    }
}


const myview = new MyView();
// 暴露到全局
window.myview = myview;
window.myview.init()